package com.kgcx.order.controller;

import com.kgcx.common.bean.RequestData;
import com.kgcx.common.bean.ReturnData;
import com.kgcx.common.constant.ResultCode;
import com.kgcx.common.controller.BaseController;
import com.kgcx.common.eum.CommonDataEeum;
import com.kgcx.common.utils.IpUtils;
import com.kgcx.common.utils.RequestParamUtil;
import com.kgcx.common.utils.XMLUtil;
import com.kgcx.order.domain.PayRecord;
import com.kgcx.order.service.PayService;
import com.kgcx.order.vo.PayInfoRequestVo;
import com.kgcx.order.vo.PayInfoResponseVo;
import com.kgcx.pay.util.PayPreInfoBean;
import com.xiaoleilu.hutool.util.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "支付接口", tags = "支付接口")
@RestController
@Slf4j
@RequestMapping("pay")
public class PayController extends BaseController {
    @Resource
    private PayService payService;

    /**
     * ===支付宝支付===
     */
    @PostMapping("driver-alipay-info")
    @ApiOperation(value = "司机端支付宝预支付接口")
    public ReturnData<?> driverAlipayInfo(@RequestBody PayInfoRequestVo payInfoRequest, HttpServletRequest request) {
        PayRecord payRecord = new PayRecord();
        PayInfoResponseVo payInfoResponseVo = new PayInfoResponseVo();
        //BeanUtils.copyProperties(payInfoRequest, payRecord);

        payRecord.setOrderNo(payInfoRequest.getOrderNo());
        payRecord.setOpenId(payInfoRequest.getOpenId());
        payRecord.setLicenseId(payInfoRequest.getLicenseId());
        payRecord.setCreateId(payInfoRequest.getUserId());

        payRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
        payRecord.setIp(IpUtils.getIpAddr(request));
        payRecord.setLineName("司机端支付宝支付");

        payRecord.setLinePrice(payRecord.getFactPrice());
        ReturnData<PayInfoResponseVo> response = new ReturnData<>(payInfoResponseVo);
        PayPreInfoBean payPreInfoBean = payService.addAlipayPayInfo(payRecord, CommonDataEeum.PAY_TYEP_DRIVER.getCode());
        if (!payPreInfoBean.getPayStatus()) {
            ReturnData<String> returnData = new ReturnData<>();
            returnData.setCode(ResultCode.FAIL);
            returnData.setMsg(payPreInfoBean.getPayInfo());
            //支付金额为0情况
            if ("PRICE_SUCCESS".equals(payPreInfoBean.getPayInfo())) {
                returnData.setCode(ResultCode.PRICE_SUCCESS);
            }
            return returnData;
        }
        payInfoResponseVo.setNonceStr(RandomUtil.randomUUID().replaceAll("-", ""));
        payInfoResponseVo.setData(payPreInfoBean.getData());
        payInfoResponseVo.setOrderNum(payPreInfoBean.getOrderNum());
        log.info(String.format("driverAlipayInfo【data】= %s。", payInfoResponseVo.getData()));
        return response;
    }

    @PostMapping("passenger-alipay-info")
    @ApiOperation(value = "乘客端支付宝预支付接口")
    public ReturnData<?> passengerAlipayInfo(@RequestBody PayInfoRequestVo payInfoRequest, HttpServletRequest request) {
        PayRecord payRecord = new PayRecord();
        PayInfoResponseVo payInfoResponseVo = new PayInfoResponseVo();
        //BeanUtils.copyProperties(payInfoRequest, payRecord);

        payRecord.setOrderNo(payInfoRequest.getOrderNo());
        payRecord.setOpenId(payInfoRequest.getOpenId());
        payRecord.setLicenseId(payInfoRequest.getLicenseId());
        payRecord.setCreateId(payInfoRequest.getUserId());

        payRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
        payRecord.setIp(IpUtils.getIpAddr(request));
        payRecord.setLineName("乘客端支付宝支付");

        payRecord.setLinePrice(payRecord.getFactPrice());
        ReturnData<PayInfoResponseVo> response = new ReturnData<>(payInfoResponseVo);
        PayPreInfoBean payPreInfoBean = payService.addAlipayPayInfo(payRecord, CommonDataEeum.PAY_TYEP_PASSENGER.getCode());
        if (!payPreInfoBean.getPayStatus()) {
            ReturnData<String> returnData = new ReturnData<>();
            returnData.setCode(ResultCode.FAIL);
            returnData.setMsg(payPreInfoBean.getPayInfo());
            //支付金额为0情况
            if ("PRICE_SUCCESS".equals(payPreInfoBean.getPayInfo())) {
                returnData.setCode(ResultCode.PRICE_SUCCESS);
            }
            return returnData;
        }
        payInfoResponseVo.setNonceStr(RandomUtil.randomUUID().replaceAll("-", ""));
        payInfoResponseVo.setData(payPreInfoBean.getData());
        payInfoResponseVo.setOrderNum(payPreInfoBean.getOrderNum());
        log.info(String.format("passengerAlipayInfo【data】= %s。", payInfoResponseVo.getData()));
        return response;
    }


    @PostMapping("ali-pay-callback")
    @ApiOperation(value = "支付宝支付回调")
    public void aliPayCallback(HttpServletRequest request, HttpServletResponse resp) {
        try {
            Map<String, String> valideData = RequestParamUtil.getAllRequestParam(request);
            String string = payService.alipayCallback(valideData);
            resp.getWriter().write(string);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }


    /**
     * =====微信支付========
     */
    @PostMapping("passenger-weChatPay-info")
    @ApiOperation(value = "乘客端微信预支付接口")
    public ReturnData<?> passengerWeChatPayInfo(@RequestBody PayInfoRequestVo payInfoRequest, HttpServletRequest request) {
        PayRecord payRecord = new PayRecord();
        PayInfoResponseVo payInfoResponseVo = new PayInfoResponseVo();

        payRecord.setOrderNo(payInfoRequest.getOrderNo());
        payRecord.setOpenId(payInfoRequest.getOpenId());
        payRecord.setLicenseId(payInfoRequest.getLicenseId());
        payRecord.setCreateId(payInfoRequest.getUserId());

        payRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
        payRecord.setIp(IpUtils.getIpAddr(request));
        payRecord.setLineName("乘客端微信支付");
        payRecord.setLicenseId(payInfoRequest.getLicenseId());
        payRecord.setLinePrice(payRecord.getFactPrice());
        ReturnData<PayInfoResponseVo> response = new ReturnData<>(payInfoResponseVo);
        PayPreInfoBean payPreInfoBean = payService.addWeChatPayInfo(payRecord, CommonDataEeum.PAY_TYEP_PASSENGER.getCode());
        if (!payPreInfoBean.getPayStatus()) {
            ReturnData<String> returnData = new ReturnData<>();
            returnData.setCode(ResultCode.FAIL);
            returnData.setMsg(payPreInfoBean.getPayInfo());
            //支付金额为0情况
            if ("PRICE_SUCCESS".equals(payPreInfoBean.getPayInfo())) {
                returnData.setCode(ResultCode.PRICE_SUCCESS);
            }
            return returnData;
        }
        payInfoResponseVo.setNonceStr(payPreInfoBean.getNonceStr());
        payInfoResponseVo.setData(payPreInfoBean.getData());
        payInfoResponseVo.setOrderNum(payPreInfoBean.getOrderNum());
        payInfoResponseVo.setPrepayId(payPreInfoBean.getPrepayId());
        payInfoResponseVo.setTimeStamp(payPreInfoBean.getTimeStamp());
        payInfoResponseVo.setPackage_str(payPreInfoBean.getPackage_str());
        payInfoResponseVo.setPartnerId(payPreInfoBean.getPartnerId());

        log.info(String.format("passenger-weChatPay-info【data】 = %s。", payInfoResponseVo.getData()));
        return response;
    }

    @PostMapping("driver-weChatPay-info")
    @ApiOperation(value = "司机端微信预支付接口")
    public ReturnData<?> driverWeChatPayInfo(@RequestBody PayInfoRequestVo payInfoRequest, HttpServletRequest request) {
        PayRecord payRecord = new PayRecord();
        PayInfoResponseVo payInfoResponseVo = new PayInfoResponseVo();

        payRecord.setOrderNo(payInfoRequest.getOrderNo());
        payRecord.setOpenId(payInfoRequest.getOpenId());
        payRecord.setLicenseId(payInfoRequest.getLicenseId());
        payRecord.setCreateId(payInfoRequest.getUserId());

        payRecord.setLicenseId(payInfoRequest.getLicenseId());
        payRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
        payRecord.setIp(IpUtils.getIpAddr(request));
        payRecord.setLineName("司机端微信支付");
        payRecord.setLinePrice(payRecord.getFactPrice());
        ReturnData<PayInfoResponseVo> response = new ReturnData<>(payInfoResponseVo);
        PayPreInfoBean payPreInfoBean = payService.addWeChatPayInfo(payRecord, CommonDataEeum.PAY_TYEP_DRIVER.getCode());
        if (!payPreInfoBean.getPayStatus()) {
            ReturnData<String> returnData = new ReturnData<>();
            returnData.setCode(ResultCode.FAIL);
            returnData.setMsg(payPreInfoBean.getPayInfo());
            //支付金额为0情况
            if ("PRICE_SUCCESS".equals(payPreInfoBean.getPayInfo())) {
                returnData.setCode(ResultCode.PRICE_SUCCESS);
            }
            return returnData;
        }
        payInfoResponseVo.setNonceStr(payPreInfoBean.getNonceStr());
        payInfoResponseVo.setData(payPreInfoBean.getData());
        payInfoResponseVo.setOrderNum(payPreInfoBean.getOrderNum());
        payInfoResponseVo.setPrepayId(payPreInfoBean.getPrepayId());
        payInfoResponseVo.setTimeStamp(payPreInfoBean.getTimeStamp());
        payInfoResponseVo.setPackage_str(payPreInfoBean.getPackage_str());
        payInfoResponseVo.setPartnerId(payPreInfoBean.getPartnerId());

        log.info(String.format("driver-weChatPay-info【data】 = %s。", payInfoResponseVo.getData()));
        return response;
    }

    @PostMapping("small-routine-weChatPay-info")
    @ApiOperation(value = "小程序端微信预支付接口")
    public ReturnData<?> smallRoutineWeChatPayInfo(@RequestBody PayInfoRequestVo payInfoRequest, HttpServletRequest request) {
        PayRecord payRecord = new PayRecord();
        PayInfoResponseVo payInfoResponseVo = new PayInfoResponseVo();

        payRecord.setOrderNo(payInfoRequest.getOrderNo());
        payRecord.setOpenId(payInfoRequest.getOpenId());
        payRecord.setLicenseId(payInfoRequest.getLicenseId());
        payRecord.setCreateId(payInfoRequest.getUserId());

        payRecord.setLicenseId(payInfoRequest.getLicenseId());
        payRecord.setCreateTime(new Timestamp(System.currentTimeMillis()));
        payRecord.setIp(IpUtils.getIpAddr(request));
        payRecord.setLineName("小程序微信支付");
        payRecord.setLinePrice(payRecord.getFactPrice());
        ReturnData<PayInfoResponseVo> response = new ReturnData<>(payInfoResponseVo);
        PayPreInfoBean payPreInfoBean = payService.addWeChatPayInfo(payRecord, CommonDataEeum.PAY_TYEP_SMALL_ROUTINE.getCode());
        if (!payPreInfoBean.getPayStatus()) {
            ReturnData<String> returnData = new ReturnData<>();
            returnData.setCode(ResultCode.FAIL);
            returnData.setMsg(payPreInfoBean.getPayInfo());
            //支付金额为0情况
            if ("PRICE_SUCCESS".equals(payPreInfoBean.getPayInfo())) {
                returnData.setCode(ResultCode.PRICE_SUCCESS);
            }
            return returnData;
        }
        payInfoResponseVo.setPrepayId(payPreInfoBean.getPrepayId());
        payInfoResponseVo.setData(payPreInfoBean.getData());
        payInfoResponseVo.setOrderNum(payPreInfoBean.getOrderNum());
        payInfoResponseVo.setNonceStr(payPreInfoBean.getNonceStr());
        payInfoResponseVo.setTimeStamp(payPreInfoBean.getTimeStamp());
        log.info(String.format("small-routine-weChatPay-info【data】 = %s。", payInfoResponseVo.getData()));
        return response;
    }

    @PostMapping("weChat-callback")
    @ApiOperation(value = "微信支付回调")
    public void weChatPayCallback(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        String resString = XMLUtil.parseRequst(req);
        Map<String, String> map = new HashMap<>();
        log.info("通知内容 = {}", resString);
        if (StringUtils.isNotBlank(resString)) {
            Map<String, String> resultMap = XMLUtil.doXMLParse(resString);
            if (null != resultMap && resultMap.size() > 0) {
                map = payService.weChatCallback(resultMap);
                log.info(String.format("处理完 = %s。", map));
                resp.getWriter().write(XMLUtil.toXml(map));
                return;
            }
        }
        map.put("return_code", "FAIL");
        map.put("return_msg", "失败");
        log.info(String.format("处理完 = %s。", map));
        resp.getWriter().write(XMLUtil.toXml(map));
    }

    /**
     * 专给监管平台提供查询
     */
    @ApiOperation(value = "监管平台经营支付信息", httpMethod = "GET", notes = "这是用来给监管平台查询经营支付信息的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = false, paramType = "query", dataType = "int", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "页容量", required = false, paramType = "query", dataType = "int", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "orderBy", value = "排序,sql格式", required = false, paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "orderNo", value = "下单订单号", required = false, paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "payOrderNo", value = "支付订单号", required = false, paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "payState", value = "结算状态:0未结算 1已结算 2未知", required = false, paramType = "query", dataType = "int", dataTypeClass = Integer.class)
    })
    @GetMapping("queryPayRecordWithPage")
    public ReturnData<List<PayRecord>> queryPayRecordWithPage() {
        RequestData rd = this.getRequestData();
        List<PayRecord> payList = payService.queryPayRecordWithPage(rd);
        return new ReturnData<>(payList);
    }

    @GetMapping("queryTotalAmount")
    @ApiOperation(value = "地税局查询接口", httpMethod = "GET", notes = "这是用来给地税局查询财务信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "beginTime", value = "开始时间", required = true, paramType = "query", dataType = "long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true, paramType = "query", dataType = "long", dataTypeClass = Long.class)
    })
    public ReturnData<Long> queryTotalAmount() {
        RequestData rd = this.getRequestData();
        Long amount = payService.queryTotalAmount(rd);
        return new ReturnData<>(amount);
    }


}
